#include "EventLoop.h"
#include "ThreadPool.h"
#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::shared_ptr;
using std::string;

ThreadPool *pool = nullptr;

class SubTask : public Task
{
private:
    string _data;
    shared_ptr<TcpConnect> _tcp;

public:
    SubTask(string data, shared_ptr<TcpConnect> ptr)
        : _data(data), _tcp{ptr} {}
    void process(void *args)
    {
        for (char &ch : _data)
        {
            ch = toupper(ch);
        }

        _tcp->sendInLoop(_data);
    }
};

void onConnect(shared_ptr<TcpConnect> ptr)
{
    cout << ptr->toString() << " handle connect!" << endl;
}

void onMessage(shared_ptr<TcpConnect> ptr)
{

    string msg = ptr->read();
    cout << ">> msg from " << ptr->peerPort() << ": " << msg;

    pool->addTask(new SubTask(msg, ptr));
}

void onClose(shared_ptr<TcpConnect> ptr)
{
    cout << ptr->toString() << " disconnect!" << endl;
}

void test()
{
    Acceptor acc{"127.0.0.1", 12345};
    acc.ready();
    pool = new ThreadPool();
    EventLoop loop{acc};

    loop.setConnectCallback(std::move(onConnect));
    loop.setHandleMessage(std::move(onMessage));
    loop.setCloseCallback(std::move(onClose));

    loop.loop();
}

int main(int args, char *argv[])
{
    test();
    return 0;
}